package com.mzj.saas.rent;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.core.AjaxResult;
import com.haixiaoke.saas.repository.core.BaseController;
import com.haixiaoke.saas.repository.core.page.TableDataInfo;
import com.haixiaoke.saas.repository.dto.ApartmentBillDTO;
import com.haixiaoke.saas.repository.exception.BizException;
import com.haixiaoke.saas.repository.pojo.ApartmentBill;
import com.haixiaoke.saas.repository.service.IApartmentBillService;
import com.haixiaoke.saas.repository.vo.ApartmentBillVo;
import com.mzj.saas.annotation.CheckAuth;
import com.mzj.saas.commons.Constant;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.PaymentTypeEnum;
import com.mzj.saas.config.pay.PayConfig;
import com.mzj.saas.constant.WxConstant;
import com.mzj.saas.mservice.sys.entity.WechatAccount;
import com.mzj.saas.mservice.sys.repository.WechatAccountRepository;
import com.mzj.saas.redis.RedisService;
import com.mzj.saas.util.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 公寓账单Controller
 *
 * @author qixi
 * @date 2023-06-16
 */
@RestController
@RequestMapping("/business/bill")
public class ApartmentBillController extends BaseController {
    @Autowired
    private IApartmentBillService apartmentBillService;

    @Autowired
    private LoginUserUtil loginUserUtil;
    @Autowired
    private WechatAccountRepository wechatAccountRepository;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WxConstant wxConstant;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询公寓账单列表
     */
    @GetMapping("/list")
    @CheckAuth
    public TableDataInfo list(ApartmentBill apartmentBill) {
        startPage();
        Long orgId = loginUserUtil.getOrgId();
        apartmentBill.setOrgId(orgId);
        List<ApartmentBillVo> list = apartmentBillService.selectApartmentBillVoList(apartmentBill);
        return getDataTable(list);
    }

    /**
     * 查询公寓账单列表
     */
    @GetMapping("/userList")
    @CheckAuth
    public TableDataInfo userList(ApartmentBill apartmentBill) {
        startPage();
        apartmentBill.setAuditStatus(ApartmentBill.BILL_AUDIT_STATUS_TRUE);
        List<ApartmentBill> list = apartmentBillService.selectApartmentBillList(apartmentBill);
        return getDataTable(list);
    }

    /**
     * 获取公寓账单详细信息
     */
    @GetMapping(value = "/{billId}")
    public AjaxResult getInfo(@PathVariable("billId") String billId) {
        return success(apartmentBillService.selectApartmentBillVoByBillId(billId));
    }

    // /**
    //  * 新增公寓账单
    //  */
    // @PostMapping
    // public AjaxResult add(@RequestBody ApartmentBill apartmentBill) {
    //     return toAjax(apartmentBillService.insertApartmentBill(apartmentBill));
    // }

    /**
     * 修改公寓账单
     */
    @PutMapping
    public AjaxResult edit(@RequestBody ApartmentBill apartmentBill) {
        return toAjax(apartmentBillService.updateApartmentBill(apartmentBill));
    }

    /**
     * 审核账单
     *
     * @param apartmentBill
     * @return
     */
    @PostMapping("/examineBill")
    @CheckAuth
    public AjaxResult examineBill(@RequestBody @Valid ApartmentBill apartmentBill) {
        return toAjax(apartmentBillService.examineApartmentBill(apartmentBill));
    }

    /**
     * 支付账单
     *
     * @param dto 账单
     * @return
     */
    @PostMapping("/payment")
    @CheckAuth
    public AjaxResult paymentBill(@RequestBody @Valid ApartmentBillDTO dto) {
        List<String> billIds = dto.getBillIds();
        if (apartmentBillService.checkBillPayState(billIds)) {
            throw new BizException("账单已支付,请勿重复提交!");
        }

        ApartmentBill apartmentBill = apartmentBillService.selectApartmentBillByBillId(billIds.get(0));
        if (ObjectUtil.isNull(apartmentBill)) {
            throw new BizException("账单不存在");
        }
        Long orgId = apartmentBill.getOrgId();


        WechatAccount account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.WECHAT.getValue());
        String ip = redisService.getValue(Constant.SPBILL_CREATE_IP);
        if (ObjectUtil.isEmpty(account)) {
            throw new BizException(Integer.valueOf(StatusCode.ERROR_CODE_10030.getErrorCode()), StatusCode.ERROR_CODE_10030.getErrorMsg());
        }
        String id = IdUtil.fastSimpleUUID();
        dto.setOutTradeNo(id);
        dto.setAppId(wxConstant.wxApartmentAppid);
        dto.setMchId(account.getMchId());
        dto.setMchApiKey(account.getMchApiKey());
        dto.setSpbillCreateIp(ip);
        dto.setWxNotifyUrl(wxConstant.wxPayApartmentBillCallbackUrl);
        dto.setUnifiedApi(payConfig.getUnifiedApi());
        Map<String, Object> resulMap = apartmentBillService.apartmentBillWXPay(dto);
        if (CollectionUtil.isNotEmpty(resulMap)) {
            // 删除缓存订单数据
            redisTemplate.opsForValue().set(ApartmentBill.REDIS_BILL_KEY + id, JSONObject.toJSONString(dto),
                    15, TimeUnit.MINUTES);
        }
        return success(resulMap);
    }


    // /**
    //  * 删除公寓账单
    //  */
    // @DeleteMapping("/{billIds}")
    // public AjaxResult remove(@PathVariable String[] billIds) {
    //     return toAjax(apartmentBillService.deleteApartmentBillByBillIds(billIds));
    // }
}
